package com.example.lzy.listviewsample.com.example.lzy.listviewsample.zdy;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.example.lzy.listviewsample.R;

import java.util.LinkedList;
import java.util.List;

public class UpdateDataActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView mListView = null;
    private Button mAddBtn = null;
    private Button mUpdateBtn = null;
    private Button mDeleteBtn = null;
    private Button mClearBtn = null;

    private MyUpdateAdapter myUpdateAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.updatedata_layout);

//        获取页面控件
    mListView = (ListView) findViewById(R.id.listview);
    mAddBtn = (Button) findViewById(R.id.add_btn);
    mUpdateBtn = (Button) findViewById(R.id.uapdat_btn);
    mDeleteBtn = (Button) findViewById(R.id.delete_btn);
    mClearBtn = (Button) findViewById(R.id.clear_btn);


    View emptyView = findViewById(R.id.text);
    mListView.setEmptyView(emptyView);

    List<UpdateData> datas = new LinkedList<UpdateData>();
    myUpdateAdapter = new MyUpdateAdapter(this,datas);
    mListView.setAdapter(myUpdateAdapter);

    mAddBtn.setOnClickListener(this);
    mUpdateBtn.setOnClickListener(this);
    mDeleteBtn.setOnClickListener(this);
    mClearBtn.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.add_btn:
                addItem();
                break;
            case R.id.uapdat_btn:
                updateData();
                break;
            case R.id.delete_btn:
                deleteItem();
                break;
            case R.id.clear_btn:
                clearData();
                break;
            default:
                break;
        }
    }

    /**
     * 增加列表项
     */
    private void addItem(){
        int position = getRandomPosition();
        myUpdateAdapter.add(position,new UpdateData(R.mipmap.ic_launcher,"随机添加"+position));
    }

    /**
     * 更新列表内容
     */
    private void updateData(){
        int position = getRandomPosition();
        myUpdateAdapter.update(position,new UpdateData(R.mipmap.ic_launcher,"更新"+getRandomNumber()));
    }

    /**
     * 删除列表项
     */
    private void deleteItem(){
        int position = getRandomPosition();
        myUpdateAdapter.remove(position);
    }

    /**
     * 清空列表数据
     */
    private void clearData(){
        myUpdateAdapter.clear();
    }

    /**
     * 获取列表随机位置
     */
    private int getRandomPosition(){
        int count = myUpdateAdapter.getCount();
        return (int) (Math.random()*count);
    }


    /**
     * 获取100以内随机数
     */
    private double getRandomNumber(){

        return Math.random()*100;
    }

}
